﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Framework;
using PlanningGIS.Util;
using PlanningGIS.ArcGIS;
using ESRI.ArcGIS.Carto;
using PlanningGIS.Win.Controls;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using PlanningGIS.MapSheet;
using PlanningGIS.Util.Log;
using PlanningGIS.MetaData;
using DevComponents.DotNetBar;

namespace PlanningGIS.Cartographic
{
    /// <summary>
    /// 导出带有图廓的地图
    /// </summary>
    public partial class CtlFrameOut : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlFrameOut()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 地图关联对象
        /// </summary>
        private IHookHelper _HookHelper = null;

        /// <summary>
        /// 地图关联对象
        /// </summary>
        public object Hook
        {
            set
            {
                _HookHelper = new HookHelper();
                _HookHelper.Hook = value;
            }
        }

        /// <summary>
        /// 获取当前的布局对象
        /// </summary>
        public object Object { get { return axPageLayoutFrame.Object; } }

        /// <summary>
        /// 绘制工具构建对象
        /// </summary>
        private ToolCreator _ToolCreator = null;

        /// <summary>
        /// 结合表选择构建对象
        /// </summary>
        private SheetCreator _SheetCreator = null;

        /// <summary>
        /// 导出操作类
        /// </summary>
        private FrameExport _Export = null;
        
        /// <summary>
        /// 初始化对象
        /// </summary>
        public void Init()
        {
            _Export = new FrameExport();
            dtimDate.Value = DateTime.Now;
            _SheetCreator = new SheetCreator(spgrdSheet);
            _SheetCreator.Hook = _HookHelper.Hook;
            _SheetCreator.IsToMap = true;
            _SheetCreator._Progressor = new Progressor() { ProgressBar = prgsor };
            List<ValueName> btns = new List<ValueName>()
            {
                new ValueName(){Value="ToolDrawRectangle",Name="绘制矩形"},
                new ValueName(){Value="ToolDrawPolygon",Name="绘制多边形"},
                new ValueName(){Value="ToolDrawCircle",Name="绘制圆"},
                new ValueName(){Value="ToolDrawLine",Name="绘制线"}
            };
            _ToolCreator = new ToolCreator(btnDrawExtent, _HookHelper.Hook);
            _ToolCreator.HideForm = true;
            _ToolCreator.Create(btns, true);
            _ToolCreator.DrawFinished += OnDrawFinished;
            regionTree.Hook = _HookHelper.Hook;
            regionTree.IsToMap = false;
            regionTree.AfterCheck += RegionTree_AfterCheck;
            List<int> scale = SheetHelper.GetScales();
            foreach (int itm in scale)
                cmbScale.Items.Add(itm);
            if (cmbScale.Items.Count > 0) cmbScale.SelectedIndex = 0;
            cmbPicFormat.Items.AddRange(new string[] { "jpg", "bmp", "tif", "pdf" });
            cmbPicFormat.SelectedIndex = 0;

            PrintHelper.SynchroPageMap(_HookHelper.Hook as IMapControl3, axPageLayoutFrame.Object as IPageLayoutControl2);
            axPageLayoutFrame.Page.Orientation = 2;
            axPageLayoutFrame.Page.FormID = esriPageFormID.esriPageFormA1;
            
            _Export._Progressor = new Progressor() { ProgressBar = prgsor };
            _Export.PageLayout = axPageLayoutFrame.Object as IPageLayoutControl3;
            axPageLayoutFrame.ZoomToWholePage();
            _Export.DrawLayout((_HookHelper.Hook as IMapControl3).Extent);            
            axPageLayoutFrame.Refresh();
           
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegionTree_AfterCheck(object sender, DevComponents.AdvTree.AdvTreeCellEventArgs e)
        {
            _SheetCreator.SelectRegion(regionTree.SelectedGeometry, 0, swtbtnExpType.Value);
        }

        /// <summary>
        /// 绘制完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnDrawFinished(object sender, DrawArgs e)
        {
            IGeometry geo = e.Geometry;
            if (sptbctlGeo.SelectedTab == sptbitmRegion)
            {
                regionTree.SelectRegion(e.Geometry, e.Shift);
                geo = regionTree.SelectedGeometry;
            }
            _SheetCreator.SelectRegion(geo, e.Shift, swtbtnExpType.Value);
            _ToolCreator?.Clear();
        }

        /// <summary>
        /// 比例尺选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbScale_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(cmbScale.Text)) return;
            if (_SheetCreator == null || _Export == null) return;

            _SheetCreator.ScaleValue = int.Parse(cmbScale.Text);
            _Export.Scale = _SheetCreator.ScaleValue;
            SheetScale st = SheetHelper.Config.ScaleTypes.FirstOrDefault(t => t.Value == _Export.Scale);
            if (st != null)
            {
                _Export.XOffset = st.XOffset;
                _Export.YOffset = st.YOffset;
            }
        }

        /// <summary>
        /// 打印设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrintSet_Click(object sender, EventArgs e)
        {
            FrmPrintSet frm = new FrmPrintSet();
            frm.LayerOut = axPageLayoutFrame.Object as IPageLayoutControl2;
            frm.ShowFromMapFrame = true;
            frm.ShowDialog();
        }

        ///// <summary>
        ///// 打印
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnPrint_Click(object sender, EventArgs e)
        //{
        //    if (!InitParam()) return;
        //    axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerHourglass;//设置鼠标
        //    try
        //    {
        //        _Export.PrintCurrent(_SheetCreator.SeletedSheet);
        //        ToastNotification.Show(this.ParentForm, "打印完成", null, 5 * 1000, eToastGlowColor.Blue, eToastPosition.MiddleCenter);
        //    }
        //    catch (Exception ex)
        //    {
        //        MsgHelper.ShowErrorMsgbox(this.ParentForm, "打印出错，请检查是否所选打印机是否已连接:" + ex.Message);
        //    }
        //    finally
        //    {
        //        axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerDefault;//设置鼠标
        //    }            
        //}

        /// <summary>
        /// 批量打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            _Export.Sheets = _SheetCreator.CheckedSheets;
            if (_Export.Sheets == null || _Export.Sheets.Count == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择图幅！");
                return;
            }
            SetParam();
            axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerHourglass;//设置鼠标
            try
            {
                _Export.PrintAll();
                ToastNotification.Show(this.ParentForm, "打印完成", null, 5 * 1000, eToastGlowColor.Blue, eToastPosition.MiddleCenter);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "打印出错，请检查是否所选打印机是否已连接:" + ex.Message);
            }
            finally
            {
                axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerDefault;//设置鼠标
            }
        }

        ///// <summary>
        ///// 导出当前图幅
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnExport_Click(object sender, EventArgs e)
        //{
        //    if (!InitParam()) return;
        //    if (folderBrowserDialog1.ShowDialog() != DialogResult.OK) return;
        //    _Export.ExportPath = folderBrowserDialog1.SelectedPath;
        //    axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerHourglass;//设置鼠标
        //    try
        //    {
        //        _Export.ExportCurrent(_SheetCreator.SeletedSheet);
        //        ToastNotification.Show(this.ParentForm, "导出完成", null, 5 * 1000, eToastGlowColor.Blue, eToastPosition.MiddleCenter);
        //    }
        //    catch (Exception ex)
        //    {
        //        MsgHelper.ShowErrorMsgbox(this.ParentForm, "导出出错:" + ex.Message);
        //    }
        //    finally
        //    {
        //        axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerDefault;//设置鼠标
        //    }
        //}

        /// <summary>
        /// 导出所有选中的图幅
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            _Export.Sheets = _SheetCreator.CheckedSheets;
            if (_Export.Sheets == null || _Export.Sheets.Count == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择图幅！");
                return;
            }
            SetParam();
            
            if (folderBrowserDialog1.ShowDialog() != DialogResult.OK) return;
            _Export.ExportPath = folderBrowserDialog1.SelectedPath;            
            axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerHourglass;//设置鼠标
            try
            {
                _Export.ExportAll();
                ToastNotification.Show(this.ParentForm, "导出完成", null, 5 * 1000, eToastGlowColor.Blue, eToastPosition.MiddleCenter);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "导出出错:" + ex.Message);
            }
            finally
            {
                axPageLayoutFrame.MousePointer = esriControlsMousePointer.esriPointerDefault;//设置鼠标
            }
        }

        /// <summary>
        /// 图廓整饰
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMapFrame_Click(object sender, EventArgs e)
        {
            if (_SheetCreator.SeletedSheet == null)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择图幅！");
                return;
            }
            SetParam();
            _Export.DrawFrameItem(_SheetCreator.SeletedSheet);            
        }
        
        /// <summary>
        /// 
        /// </summary>
        private void SetParam()
        {
            _Export.Scale = _SheetCreator.ScaleValue;
            _Export.ExportType = cmbPicFormat.Text;
            _Export.HasMeta = epdpnlMeta.Expanded;
            _Export.MetaValues = new Dictionary<string, string>();
            if (epdpnlMeta.Expanded)
            {
                _Export.MetaValues.Add(MetaHelper.Key_CZDW, txtUnit.Text);
                _Export.MetaValues.Add(MetaHelper.Key_CZSJ, dtimDate.Value.ToString("yyyy-MM-dd"));
                _Export.MetaValues.Add(MetaHelper.Key_HTY, txtCHY.Text);
                _Export.MetaValues.Add(MetaHelper.Key_CLY, txtCTY.Text);
                _Export.MetaValues.Add(MetaHelper.Key_JCY, txtJCY.Text);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void Clear()
        {
            _SheetCreator?.ClearElement();
            _ToolCreator?.Clear();
            regionTree.Clear();
        }

    }
}
